import fs from 'fs';
import path from 'path';
import ts from 'typescript';
import { mergeTranslations } from './merge-translations.js';

// 配置
const SRC_DIR = './src';
const TRANSLATION_FILES = {
  en: './src/i18n/locales/en/translation.json',
  zh: './src/i18n/locales/zh/translation.json'
};

// 排除的路径
const EXCLUDE_PATHS = [
  'node_modules',
  'i18n',
  'routeTree.gen.ts'
];

// 支持的文件扩展名
const FILE_EXTENSIONS = ['.ts', '.tsx'];

// 存储提取的字符串
let extractedStrings = new Map();

// 检查是否应该排除该路径
function shouldExclude(filePath) {
  return EXCLUDE_PATHS.some(exclude => filePath.includes(exclude));
}

// 生成翻译键
function generateKey(file, text) {
  const relativePath = path.relative(SRC_DIR, file);
  const dir = path.dirname(relativePath);
  const fileName = path.basename(relativePath, path.extname(relativePath));
  
  // 清理文本
  const cleanText = text
    .replace(/[^a-zA-Z0-9\s]/g, '')
    .replace(/\s+/g, ' ')
    .trim()
    .replace(/\s/g, '');
    
  // 生成键名
  let key = dir.replace(/\//g, '.').replace(/\\/g, '.');
  if (key) key += '.';
  key += `${fileName}.${cleanText}`;
  
  return key.toLowerCase();
}

// 访问器函数，用于遍历 AST 节点
function visitNode(node, file, sourceFile) {
  // 提取字符串字面量
  if (ts.isStringLiteral(node) && node.text.trim()) {
    const text = node.text.trim();
    // 过滤条件：长度大于2且不全是数字
    if (text.length > 2 && !/^[0-9\s]+$/.test(text)) {
      const key = generateKey(file, text);
      extractedStrings.set(key, {
        text,
        file,
        line: sourceFile.getLineAndCharacterOfPosition(node.pos).line + 1
      });
    }
  }
  
  // 提取 JSX 文本
  if (ts.isJsxText(node) && node.text.trim()) {
    const text = node.text.trim();
    if (text.length > 2 && !/^[0-9\s]+$/.test(text)) {
      const key = generateKey(file, text);
      extractedStrings.set(key, {
        text,
        file,
        line: sourceFile.getLineAndCharacterOfPosition(node.pos).line + 1
      });
    }
  }
  
  // 递归访问子节点
  ts.forEachChild(node, childNode => visitNode(childNode, file, sourceFile));
}

// 解析单个文件
function parseFile(file) {
  try {
    const sourceCode = fs.readFileSync(file, 'utf-8');
    const sourceFile = ts.createSourceFile(
      file,
      sourceCode,
      ts.ScriptTarget.Latest,
      true
    );
    
    visitNode(sourceFile, file, sourceFile);
  } catch (error) {
    console.error(`Error parsing file ${file}:`, error.message);
  }
}

// 递归扫描目录
function scanDirectory(dir) {
  const files = fs.readdirSync(dir);
  
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory()) {
      scanDirectory(filePath);
    } else if (stat.isFile() && FILE_EXTENSIONS.includes(path.extname(filePath))) {
      if (!shouldExclude(filePath)) {
        parseFile(filePath);
      }
    }
  });
}

// 更新翻译文件
function updateTranslationFiles() {
  // 读取现有翻译
  Object.keys(TRANSLATION_FILES).forEach(lang => {
    const newTranslations = {};
    
    // 构建新提取的翻译对象
    extractedStrings.forEach((value, key) => {
      newTranslations[key] = lang === 'en' ? value.text : `【待翻译】${value.text}`;
    });
    
    if (fs.existsSync(TRANSLATION_FILES[lang])) {
      // 读取现有翻译
      const content = fs.readFileSync(TRANSLATION_FILES[lang], 'utf-8');
      const existingTranslations = JSON.parse(content);
      
      // 使用合并函数合并现有翻译和新提取的翻译
      const mergedTranslations = mergeTranslations(existingTranslations, newTranslations);
      
      // 保存文件
      fs.writeFileSync(TRANSLATION_FILES[lang], JSON.stringify(mergedTranslations, null, 2));
      console.log(`Updated ${TRANSLATION_FILES[lang]} with merge mode`);
    } else {
      // 创建新文件
      fs.writeFileSync(TRANSLATION_FILES[lang], JSON.stringify(newTranslations, null, 2));
      console.log(`Created ${TRANSLATION_FILES[lang]}`);
    }
  });
}

// 主函数
function main() {
  console.log('Starting TypeScript i18n extraction...');
  
  // 扫描源代码目录
  scanDirectory(SRC_DIR);
  
  console.log(`Found ${extractedStrings.size} strings to translate`);
  
  // 更新翻译文件
  updateTranslationFiles();
  
  // 输出报告
  console.log('\nExtraction report:');
  extractedStrings.forEach((value, key) => {
    console.log(`${key}: ${value.text} (${value.file}:${value.line})`);
  });
  
  console.log('\nDone!');
}

// 运行主函数
main();